package com.idbk.chargestation.activity.user;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.idbk.chargestation.R;
import com.idbk.chargestation.api.APIForFile;
import com.idbk.chargestation.api.ChargeStationURL;
import com.idbk.chargestation.app.ManagerCache;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.bean.JsonCarMsgList;
import com.idbk.chargestation.bean.JsonCarTypes;
import com.idbk.chargestation.bean.JsonCertification;
import com.idbk.chargestation.dialog.DialogCarNum;
import com.idbk.chargestation.fragment.FragmentCarBrands;
import com.idbk.chargestation.fragment.FragmentCarTypes;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GsonUtils;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;


/**
 * 车主认证
 *
 * @author lupc, zhx
 */
public class ActivityCertification extends BaseActivity implements OnClickListener {

    private static final String TAG = ActivityCertification.class.getSimpleName();
    public final static String CAMERA_FILE_NAME = "car_certification_camera.jpg";
    public final static String CROPED_FILE_NAME = "car_certification_croped.jpg";
    public final static String KEY_CERTIFICATION_ACTION = "key_action";
    public final static int ACTION_ADD_CERTIFICATION = 1;
    public final static int ACTION_MODIFY_CERTIFICATION = 2;
    private final int REQUEST_CODE_CAMERA = 99;
    private int mCertificationAction = ACTION_ADD_CERTIFICATION;
    private int mChargePortType;//选择状态记住,充电接口类型

    private Context mContext;
    private EditText mEdtLicenseNum, mEdtMotorNum, mEdtCarChassisNum;
    private TextView mTexProvince;//车牌归属地
    private TextView mTexCarBrand, mTexCarType, mTexChargeType;//品牌和车型,充电接口类型
    private ImageView mImgCarLogo, mImgDrivingLicense;//汽车品牌logo, 行驶证

    /* 侧滑菜单 */
    private DrawerLayout mDrawerLayout;//打开和关闭侧滑菜单
    private FrameLayout mFrameLayout;//侧滑显示布局
    private FragmentCarBrands mFragmentBrands;//汽车品牌选择
    private FragmentCarTypes mFragmentTypes;//汽车品牌选择

    private String[] aTypes = {"通用", "直流", "单相交流", "三相交流"};
    private List<Integer> mCarIdList;//存放品牌对应车型id
    private DialogCarNum mDialog;//车牌归属地选择Dialog
    private String mCarBrand, mTempUrl;//选择的汽车品牌

    private Uri mOrigUri, mCropUri;//照相机获取的原始图片URI，裁剪后的URI
    private JsonCertification mData;
    private ProgressDialog mProgressDialog;
    private final FragmentManager mFragmentManager = getSupportFragmentManager();
    private RequestCall mRequest;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_certification);

        mContext = ActivityCertification.this;

        initView();

        initData();
    }

    private void initView() {
        initLayoutView();
        initWidgetView();
        initOnClickView();
    }

    private void initLayoutView() {
        mDialog = new DialogCarNum(mContext, this);

        mFragmentBrands = (FragmentCarBrands) getSupportFragmentManager().findFragmentById(R.id.fragment_car_brand);
        mFragmentTypes = (FragmentCarTypes) getSupportFragmentManager().findFragmentById(R.id.fragment_car_type);
        mFrameLayout = (FrameLayout) findViewById(R.id.drawer_brand_list);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        if (mDrawerLayout != null) {
            mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);//关闭手势滑动
        }
    }

    private void initWidgetView() {
        mEdtLicenseNum = (EditText) findViewById(R.id.edit_car_number);
        mEdtMotorNum = (EditText) findViewById(R.id.edit_motor);
        mEdtCarChassisNum = (EditText) findViewById(R.id.edit_carriage);
        mTexChargeType = (TextView) findViewById(R.id.certification_type);
        mTexProvince = (TextView) findViewById(R.id.license_car_city);
        mTexCarBrand = (TextView) findViewById(R.id.certification_brand);
        mTexCarType = (TextView) findViewById(R.id.certification_car_type);
        mImgCarLogo = (ImageView) findViewById(R.id.certification_icon);
        mImgDrivingLicense = (ImageView) findViewById(R.id.certification_photo);
    }

    @SuppressWarnings("ConstantConditions")
    private void initOnClickView() {
        findViewById(R.id.toolbar_back).setOnClickListener(this);
        findViewById(R.id.certification_commit).setOnClickListener(this);
        findViewById(R.id.number_chose).setOnClickListener(this);
        findViewById(R.id.linear_brand).setOnClickListener(this);
        findViewById(R.id.linear_type).setOnClickListener(this);
        findViewById(R.id.certification_upload).setOnClickListener(this);
    }

    private void initData() {
        mCarIdList = new ArrayList<Integer>();
        initDefaultData();
        initIntentData();
    }

    private void initDefaultData() {
        mTexProvince.setText("京");
        mTexChargeType.setText("通用");
    }

    private void initIntentData() {
        //判断是否修改认证信息
        mCertificationAction = getIntent().getIntExtra(KEY_CERTIFICATION_ACTION, ACTION_ADD_CERTIFICATION);
        if (mCertificationAction == ACTION_MODIFY_CERTIFICATION) {
            bindData();
        } else {
            mData = new JsonCertification();
        }
    }

    //显示已认证信息
    private void bindData() {
        mData = getIntent().getParcelableExtra(JsonCertification.KEY);
        if (mData != null) {
            //根据车牌号码，分离出：车牌归属地、牌号
            mTexProvince.setText(mData.vehicleNum.subSequence(0, 1));
            mEdtLicenseNum.setText(mData.vehicleNum.subSequence(1, mData.vehicleNum.length()));

            mTexCarBrand.setText(mData.brandName);//汽车品牌
            mTexCarType.setText(mData.typeName);//汽车类型
            mEdtMotorNum.setText(mData.engineNum);//发动机编号
            mEdtCarChassisNum.setText(mData.chassisNum);//车架号
            mTexChargeType.setText(mData.chargePort);//充电接口类型

            String brandUrl = ChargeStationURL.getAbsoluteApiUrlFromRoot(mData.logoURL);//获取品牌图片地址
            String licenseUrl = ChargeStationURL.getAbsoluteApiUrlFromRoot(mData.photoURL);//获取行驶证图片地址
            Picasso.with(mContext).load(brandUrl).into(mImgCarLogo);
            Picasso.with(mContext).load(licenseUrl).into(mImgDrivingLicense);

            //初始化充电接口选择
            for (int i = 0; i < 4; i++) {
                if (aTypes[i].equals(mData.chargePort)) {
                    mChargePortType = i;
                    break;
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //判断抽屉是否显示
            if (mDrawerLayout.isDrawerOpen(mFrameLayout)) {
                mDrawerLayout.closeDrawer(mFrameLayout);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.linear_type: //充电接口类型
                chooseChargeType();
                break;
            case R.id.linear_brand: //车型品牌
                chooseCarBrand();
                break;
            case R.id.certification_commit: //提交
                commit();
                break;
            case R.id.number_chose: //车牌号区域选择
                mDialog.show();
                break;
            case R.id.certification_upload: //上传行驶证
                upload();
                break;
            default:
                break;
        }
    }

    private void chooseCarBrand() {
        mDrawerLayout.openDrawer(mFrameLayout);//打开抽屉
        loadCarMessage();//读取汽车品牌和型号
    }

    //读取汽车品牌和型号信息
    private void loadCarMessage() {
        final ArrayList<String> names = new ArrayList<String>();
        mFragmentManager.beginTransaction().show(mFragmentBrands).hide(mFragmentTypes).commit();
        setBackClickToType();
        setItemClickToBrand(names);
        setItemClickToType(names);
    }

    private void setBackClickToType() {
        mFragmentTypes.btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mFragmentManager.beginTransaction().show(mFragmentBrands).hide(mFragmentTypes).commit();
            }
        });
    }

    private void setItemClickToBrand(final ArrayList<String> names) {
        //传值到车型Fragment
        mFragmentBrands.mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long arg3) {
                JsonCarMsgList mList = mFragmentBrands.getResult();//返回搜索结果
                if (mList != null) {
                    mCarBrand = mList.vehicleBrands.get(position).brandName;//记住选择品牌
                    mTempUrl = ChargeStationURL.getAbsoluteApiUrlFromRoot(mList.vehicleBrands.get(position).logoURL);//获取图片地址
                    names.clear();//清除集合
                    mCarIdList.clear();
                    //遍历所有车型
                    for (JsonCarTypes types : mList.vehicleTypes) {
                        //找到车型Id对应的车辆品牌Id
                        if (types.vehicleBrandId == mList.vehicleBrands.get(position).id) {
                            names.add(types.typeName);
                            mCarIdList.add(types.id);
                        }
                    }
                    mData.vehicleBrandId = mList.vehicleBrands.get(position).id;//品牌Id

                    mFragmentTypes.setupData(names);
                    mFragmentManager.beginTransaction().hide(mFragmentBrands).show(mFragmentTypes).commit();//隐藏汽车品牌Fragment
                } else {
                    mDrawerLayout.closeDrawer(mFrameLayout);//关闭抽屉
                    Toast.makeText(mContext, "没有找到对应的车型，请刷新", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void setItemClickToType(final ArrayList<String> names) {
        //选择车型后返回
        mFragmentTypes.mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long arg3) {
                mDrawerLayout.closeDrawer(mFrameLayout);//关闭抽屉
                mTexCarBrand.setText(mCarBrand);//汽车品牌
                mTexCarType.setText(names.get(position));//汽车型号
                mData.vehicleTypeId = mCarIdList.get(position);//车型Id
                Picasso.with(mContext).load(mTempUrl).into(mImgCarLogo);//显示汽车logo
                if (mCertificationAction == ACTION_MODIFY_CERTIFICATION) {
                    clearEditText();
                }

            }
        });
    }

    private void clearEditText() {
        //重新选择车型后重置所有输入信息
        mEdtLicenseNum.setText("");
        mEdtMotorNum.setText("");
        mEdtCarChassisNum.setText("");
    }


    private void chooseChargeType() {
        new AlertDialog.Builder(mContext)
                .setTitle("充电接口类型")
                .setSingleChoiceItems(aTypes, mChargePortType, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTexChargeType.setText(aTypes[which]);
                        mChargePortType = which;
                        dialog.dismiss();
                    }
                }).show();
    }

    //选择图片上传
    private void upload() {
        //判断是否挂载了SD卡
        if (!ManagerCache.isSDCARDMounted()) {
            Snackbar.make(mImgDrivingLicense, "错误，无法找到SD卡！", Snackbar.LENGTH_LONG).show();
            return;
        }
        new AlertDialog.Builder(mContext).setCancelable(true)
                .setItems(new String[]{"相册", "相机"}, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            startPhotoChose();//从相册中选择
                        } else {
                            checkAndStartTakePhoto();//拍照选择
                        }
                        dialog.dismiss();
                    }
                }).show();
    }

    //从相册中选取
    private void startPhotoChose() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    Const.CODE_REQUEST_GETIMAGE_BYCROP);
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    Const.CODE_REQUEST_GETIMAGE_BYCROP);
        }
    }

    //从相机选取
    private void checkAndStartTakePhoto() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
        } else {
            startTakePhoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                startTakePhoto();
            } else {
                showMissingPermissionDialog();
            }
        }
    }

    //拍照
    private void startTakePhoto() {
        //开始拍照
        File out = new File(getExternalFilesDir(null), CAMERA_FILE_NAME);
        Uri uri = Uri.fromFile(out);
        mOrigUri = uri;

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, Const.CODE_REQUEST_GETIMAGE_BYCAMARA);
    }

    /**
     * 裁剪后 显示图片
     */
    private void handlePhoto() {
        File file = new File(getExternalFilesDir(null), CROPED_FILE_NAME);
        if (!file.exists()) {
            Snackbar.make(mImgDrivingLicense, "错误，无法找到剪切图！", Snackbar.LENGTH_LONG).show();
            return;
        }
        mImgDrivingLicense.setImageBitmap(BitmapFactory.decodeFile(file.getPath()));
        //

    }

    //图片的绝对路径
    private Uri getUploadTempFile() {
        //图片的绝对路径
        File f = new File(getExternalFilesDir(null), CROPED_FILE_NAME);
        mCropUri = Uri.fromFile(f);
        return mCropUri;
    }

    private boolean checkInput() {
        //品牌车型
        if (mTexCarBrand.getText().toString().equals("")) {
            Toast.makeText(mContext, "请选择你的汽车品牌和车型", Toast.LENGTH_SHORT).show();
            return false;
        }
        //行驶证--增加模式
        if (mCertificationAction == ACTION_ADD_CERTIFICATION && mCropUri == null) {
            Toast.makeText(mContext, "请上传行驶证照片", Toast.LENGTH_SHORT).show();
            return false;
        }
        //车牌号
        if (mEdtLicenseNum.getText().toString().equals("")) {
            Toast.makeText(mContext, "请输入车牌号码", Toast.LENGTH_SHORT).show();
            return false;
        }
        //发动机编号
        if (mEdtMotorNum.getText().toString().equals("") ||
                mEdtMotorNum.getText().toString().length() < 6) {
            Toast.makeText(mContext, "请输入正确的车辆发动机编码", Toast.LENGTH_SHORT).show();
            return false;
        }
        //车架号
        if (mEdtCarChassisNum.getText().toString().equals("") ||
                mEdtCarChassisNum.getText().toString().length() < 6) {
            Toast.makeText(mContext, "请输入正确的车架号", Toast.LENGTH_SHORT).show();
            return false;
        }
        //充电接口类型
        if (mTexChargeType.getText().toString().equals("")) {
            Toast.makeText(mContext, "请选择车辆充电接口类型", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void showProgress() {
        mProgressDialog = ProgressDialog.show(mContext, null, "提交中...", true, true, new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (mRequest != null) {
                    mRequest.cancel();
                }
            }
        });
    }

    private void dismissProgress() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    //提交认证
    private void commit() {
        if (checkInput()) {
            getData();
            commitData();
        }
    }

    private void getData() {
        //准备数据
        mData.vehicleNum = mTexProvince.getText().toString() + mEdtLicenseNum.getText().toString();
        mData.engineNum = mEdtMotorNum.getText().toString();
        mData.chassisNum = mEdtCarChassisNum.getText().toString();
    }

    private void commitData() {
        showProgress();
        //判断修改认证和添加认证
        if (mCertificationAction == ACTION_ADD_CERTIFICATION) {
            addCarCertification();
        } else {
            if (mCropUri == null) {
                modifyCarCertificationNoPic();
            } else {
                modifyCarCertification();
            }
        }
    }

    private void addCarCertification() {
        mRequest = APIForFile.addCarMessage(mData.vehicleBrandId, mData.vehicleTypeId, mData.vehicleNum,
                mData.engineNum, mData.chassisNum, mChargePortType, getSmallPicFile(), mCallBack);
    }

    private void modifyCarCertificationNoPic() {
        mRequest = APIForFile.modifyCarMessageNoPic(mData.id, mData.vehicleBrandId, mData.vehicleTypeId,
                mData.vehicleNum, mData.engineNum, mData.chassisNum, mChargePortType, mCallBack);
    }

    private void modifyCarCertification() {
        mRequest = APIForFile.modifyCarMessage(mData.id, mData.vehicleBrandId, mData.vehicleTypeId, mData.vehicleNum,
                mData.engineNum, mData.chassisNum, mChargePortType, getSmallPicFile(), mCallBack);
    }

    private Callback<String> mCallBack = new StringCallback() {

        @Override
        public void onResponse(String response, int id) {
            JsonBase result = GsonUtils.toBean(JsonBase.class, response);
            if (handleResponseStatus(result)) {
                Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onAfter(int id) {
            super.onAfter(id);
            dismissProgress();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Const.CODE_REQUEST_GETIMAGE_BYCROP) {
                startActionCrop(intent.getData());//处理图片
            } else if (requestCode == Const.CODE_REQUEST_GETIMAGE_BYCAMARA) {
                startActionCrop(mOrigUri);//处理图片
            } else if (requestCode == Const.CODE_REQUEST_GETIMAGE_BYSDCARD) {
                handlePhoto();
            }
        }
    }

    //开始裁剪图片
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", getUploadTempFile());
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        startActivityForResult(intent, Const.CODE_REQUEST_GETIMAGE_BYSDCARD);
    }

    //压缩图片大小
    private File getSmallPicFile() {
        Bitmap photo = BitmapFactory.decodeFile(mCropUri.getPath());
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 9, stream);//将图片压缩到最小
        File file = new File(mCropUri.getPath());
        try {
            boolean isCreate = file.createNewFile();
            Log.e(TAG, "getSmallPicFile file.createNewFile() : " + isCreate );
            FileOutputStream fs = new FileOutputStream(file);
            if (photo.compress(Bitmap.CompressFormat.JPEG, 9, fs)) {
                fs.flush();
                fs.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    //设置车牌所属区域
    public void setCarNum(String number) {
        mTexProvince.setText(number);
    }

}
